package com.hycc.base;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCLock {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(()->{for (int i = 0; i < 10; i++) data.increment(); },"a").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.decrement(); },"b").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.increment(); },"c").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.decrement(); },"d").start();

    }
}

//判断等待，业务，通知
class Data2{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    public void increment(){
        lock.lock();
        try {
            while(number!=0){
                //等待
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"-->"+number);
            //通知
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void decrement(){
        lock.lock();
        try {

            while(number==0){
                //等待
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"-->"+number);
            //通知
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}